package com.ym.medical.service.impl;

import cn.hutool.core.date.DateUtil;
import cn.hutool.extra.spring.SpringUtil;
import com.ym.base.enums.FlagEnum;
import com.ym.core.exception.BusinessException;
import com.ym.core.utils.tkmybatis.BaseSVImpl;
import com.ym.core.utils.tkmybatis.TK;
import com.ym.medical.dao.OpenStudioAppDao;
import com.ym.medical.domain.bo.PushBean;
import com.ym.medical.domain.bo.PushBeanExtraVo;
import com.ym.medical.domain.entity.*;
import com.ym.medical.domain.param.OpenStudioAppQueryParam;
import com.ym.medical.domain.vo.OpenStudioAppVo;
import com.ym.medical.enums.DoctorStudioStatusEnum;
import com.ym.medical.enums.StudioAppStatusEnum;
import com.ym.medical.enums.StudioPersonnelRelEnum;
import com.ym.medical.enums.StudioReviewStatusEnum;
import com.ym.medical.service.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 工作室开通申请Service业务层处理
 *
 * @author ym
 * @date 2020-08-24
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class OpenStudioAppSVImpl extends BaseSVImpl<OpenStudioAppEntity, OpenStudioAppDao> implements IOpenStudioAppSV {


	@Autowired
	private IStudioPersonnelSV studioPersonnelSV;

	@Autowired
	private IDoctorStudioSV doctorStudioSV;

	@Autowired
	private IJpushAccountSV jpushAccountSV;

	@Autowired
	private IDoctorStudioPricingSV doctorStudioPricingSV;

	@Autowired
	private IStudioPersonServiceSV studioPersonServiceSV;

	@Autowired
	private IUserSV userSV;

	@Autowired
	private IDoctorServiceItemSV doctorServiceItemSV;

	@Override
	public void saveStudioApp(OpenStudioAppEntity openStudioApp, Long currId) {
		//  查看医生是否开通健康服务
		int count = doctorServiceItemSV.countByParams(DoctorServiceItemEntity.builder().build().builder().doctId(currId).isOpen(FlagEnum.IS.getKey()).build());
		if (count == 0) {
			throw new BusinessException("请先确保设置健康服务，且状态为已开通！");
		}
		// 查看是否已经开通工作室
		count = doctorStudioSV.countByParams(TK.selectWhere(DoctorStudioEntity.class).andEqualTo(DoctorStudioEntity::getBelongPerson,currId).end());
		if (count > 0) {
			throw new BusinessException("您的工作室申请已开通，请退出重新登录查看！");
		}
		if (StringUtils.isEmpty(openStudioApp.getId())) {
			//新增
			openStudioApp.setDoctId(currId);
			openStudioApp.setState(StudioAppStatusEnum.TO_AUDIT.getKey());
			this.insert(openStudioApp);
		} else {
			//修改,重新发起申请
			openStudioApp.setState(StudioAppStatusEnum.TO_AUDIT.getKey());
			openStudioApp.setAppTime(new Date());
			this.updateById(openStudioApp);
		}
	}


	@Override
	public void applicationReviewAudit(Long[] ids, Long auditPerson, String state, String remark) {
		OpenStudioAppEntity update = new OpenStudioAppEntity();
		if (state.equals(StudioAppStatusEnum.HAVE_BEEN_THROUGH.getKey())) {
			for (Long id : ids) {
				// 查询是否审核通过
				OpenStudioAppEntity only = this.selectById(id);
				if (!only.getState().equals(StudioAppStatusEnum.TO_AUDIT.getKey())) {
					throw new BusinessException("请勿重复审核:" + only.getDsName());
				}
				// 查询该医生是否已经有工作室
				int count = doctorStudioSV.countByParams(DoctorStudioEntity.builder().belongPerson(only.getDoctId()).build());
				if (count > 0) {
					throw new BusinessException("该医生已经开通工作室！无法再次开通" + only.getDsName());
				}
				only.setRemarks(remark);
				update.setId(only.getId());
				update.setState(state);
				this.updateById(update);
				// 插入审核记录表
				OpenStudioReviewEntity openStudioReview = new OpenStudioReviewEntity();
				openStudioReview.setAppId(only.getId());
				openStudioReview.setReviewId(auditPerson);
				openStudioReview.setState(StudioReviewStatusEnum.THROUGH.getKey());
				openStudioReview.setReviewOpinion(remark);
				openStudioReview.setReviewTime(new Date());
				SpringUtil.getBean(IOpenStudioReviewSV.class).insert(openStudioReview);
				// 成立工作室
				DoctorStudioEntity doctorStudio = new DoctorStudioEntity();
				doctorStudio.setBelongPerson(only.getDoctId());
				doctorStudio.setDsName(only.getDsName());
				doctorStudio.setDescription(only.getDescription());
				doctorStudio.setState(DoctorStudioStatusEnum.OPEN.getKey());
				doctorStudio.setCreateTime(new Date());
				doctorStudioSV.insert(doctorStudio);
				// 将申请的医生加入工作室
				StudioPersonnelEntity studioPersonnel = new StudioPersonnelEntity();
				studioPersonnel.setDsId(doctorStudio.getId());
				studioPersonnel.setDoctId(only.getDoctId());
				studioPersonnel.setAdmsStateDoctor(FlagEnum.IS.getKey());
				studioPersonnel.setAdmsStateStudio(FlagEnum.IS.getKey());
				studioPersonnel.setRelType(StudioPersonnelRelEnum.I_AM.getKey());
				// todo 免打扰字段不见了
				//studioPersonnel.setDisturbType(FlagEnum.NO.getKey());
				//studioPersonnel.setDisturbStart(new Date());
				//studioPersonnel.setDisturbEnd(new Date());
				studioPersonnel.setIsPriorityOrder(FlagEnum.IS.getKey());
				studioPersonnel.setIsTop(FlagEnum.IS.getKey());
				studioPersonnel.setIsAutoReply(FlagEnum.IS.getKey());
				studioPersonnel.setCreateTime(new Date());
				studioPersonnel.setDeleted(FlagEnum.NO.getKey());
				studioPersonnelSV.insert(studioPersonnel);
				// 工作室分成定价设置
				String serviceItem = only.getServiceItem();
				String proportion = only.getProportion();
				String price = only.getPrice();
				if (org.apache.commons.lang3.StringUtils.isNotBlank(serviceItem)) {
					String[] items = serviceItem.split(",");
					String[] proportions = proportion.split(",");
					String[] prices = price.split(",");
					for (int i = 0; i < items.length; i++) {
						DoctorStudioPricingEntity doctorStudioPricing = new DoctorStudioPricingEntity();
						doctorStudioPricing.setStudioId(doctorStudio.getId());
						doctorStudioPricing.setServiceId(items[i]);
						doctorStudioPricing.setProportion(new BigDecimal(proportions[i]));
						doctorStudioPricing.setState(FlagEnum.IS.getKey());
						doctorStudioPricing.setCreateTime(new Date());
						doctorStudioPricingSV.insert(doctorStudioPricing);
						StudioPersonServiceEntity studioPersonService = new StudioPersonServiceEntity();
						studioPersonService.setServiceId(items[i]);
						studioPersonService.setStudioPersonId(studioPersonnel.getId());
						studioPersonService.setProportion(new BigDecimal(proportions[i]));
						studioPersonService.setState(FlagEnum.IS.getKey());
						studioPersonService.setPrice(new BigDecimal(prices[i]));
						studioPersonService.setCreateTime(new Date());
						studioPersonServiceSV.insert(studioPersonService);
					}
				}
				// 发送推送给申请人
				PushBean pushBean = new PushBean();
				pushBean.setAlert("工作室来新消息了！");
				PushBeanExtraVo pushBeanExtra = new PushBeanExtraVo();
				pushBeanExtra.setBusinessId(only.getId().toString());
				pushBeanExtra.setMsgTypeParent("02");
				pushBeanExtra.setMsgTypeSub("04");
				pushBeanExtra.setStatus("03");
				pushBeanExtra.setPushWho(userSV.selectById(only.getDoctId()));
				pushBeanExtra.setTime(DateUtil.now());
				pushBean.setExtras(pushBeanExtra);
				jpushAccountSV.pushMessage( pushBean,true);
			}
		} else if (state.equals(StudioAppStatusEnum.HAS_BEEN_REJECTED.getKey())) {
			//拒绝
			for (Long id : ids) {
				// 查询是否审核通过
				OpenStudioAppEntity only = this.selectById(id);
				if (!only.getState().equals(StudioAppStatusEnum.TO_AUDIT.getKey())) {
					throw new BusinessException("请勿重复审核工作室:" + only.getDsName());
				}
				only.setRemarks(remark);
				update.setId(id);
				update.setState(state);
				this.updateById(update);
				// 插入审核记录表
				OpenStudioReviewEntity openStudioReview = new OpenStudioReviewEntity();
				openStudioReview.setAppId(only.getId());
				openStudioReview.setReviewId(auditPerson);
				openStudioReview.setState(FlagEnum.NO.getKey());
				openStudioReview.setReviewOpinion(remark);
				openStudioReview.setReviewTime(new Date());
				SpringUtil.getBean(IOpenStudioReviewSV.class).insert(openStudioReview);
				// 发送推送给申请人
				PushBean pushBean = new PushBean();
				pushBean.setAlert("工作室来新消息了！");
				PushBeanExtraVo pushBeanExtra = new PushBeanExtraVo();
				pushBeanExtra.setBusinessId(only.getId().toString());
				pushBeanExtra.setContent(null);
				pushBeanExtra.setMsgTypeParent("02");
				pushBeanExtra.setMsgTypeSub("04");
				pushBeanExtra.setStatus("02");
				pushBeanExtra.setPushWho(userSV.selectById(only.getDoctId()));
				pushBeanExtra.setTime(DateUtil.now());
				pushBean.setExtras(pushBeanExtra);
				jpushAccountSV.pushMessage(pushBean,true);
			}
		}
	}

	@Override
	public List<OpenStudioAppVo> applicationReviewList(OpenStudioAppQueryParam queryParam) {
		List<OpenStudioAppVo> data = mapper.applicationReviewList(queryParam);
		return data;
	}
}
